package cc.wsyw126.java.nowcoder.leetCode;

import cc.wsyw126.java.lintCode.convert_binary_search_tree_to_doubly_linked_list.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by dp on 2017/4/20.
 *
 * Given a binary tree, find its minimum depth.
 * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
 */
public class MinimumDepthOfBinaryTree {
    public int run(TreeNode root) {
        int result = 0;
        if (root == null) return result;
        TreeNode flag = new TreeNode(Integer.MIN_VALUE);
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        q.add(flag);
        while (!q.isEmpty()) {
            TreeNode poll = q.poll();
            if (poll == flag) {
                result++;
                if (q.isEmpty()) break;
                q.add(poll);
            } else {
                if (poll.left == null && poll.right == null) {
                    result++;
                    break;
                }
                if (poll.left != null) {
                    q.add(poll.left);
                }
                if (poll.right != null) {
                    q.add(poll.right);
                }
            }
        }
        return result;
    }




}
